package com.script

import com.utils.YamlUtil
import org.apache.logging.log4j.kotlin.logger
import com.utils.SFTPUtil
import com.utils.ScriptUtils.appConfig
import com.utils.ScriptUtils.script
import kotlin.collections.get


script.methodMap["runSFTP"] = ::runSFTP

fun runSFTP(pushData: String) {

    val script = pushData
    println(script)
    logger.info(script)
    val lists = script.split(" ")

    if (lists.isEmpty() || lists.size % 2 != 0) {
        println("错误的数量=$lists")
        return
    }
    val uploadFileList = mutableListOf<String>()
    val deleteFileList = mutableListOf<String>()
    var parentPath = ""
    for (i in lists.indices) {
        if (lists[i] == "parent") {
            parentPath = lists[i + 1]
        } else if (lists[i] == "addFile") {
            val adds = lists[i + 1].split(",")
            for (value in adds) {
                uploadFileList.add(value)
            }
        } else if (lists[i] == "deleteFile") {
            val deletes = lists[i + 1].split(",");
            for (value in deletes) {
//                println(value, parentPath)
                deleteFileList.add(value.removePrefix(parentPath))
            }
        }
    }

    val sftpMap = appConfig.user[YamlUtil.unpackEnvName]!!["sftp"] as Map<String, String>
    val sftpUtil = SFTPUtil(
        sftpMap.get("sftpName"),
        sftpMap.get("sftpPsd"),
        sftpMap.get("sftpIp"),
        sftpMap.get("sftpPort")!!.toInt()
    )
    val login = sftpUtil.login()

    if (login) {
        // 删除的文件
        if (deleteFileList.isNotEmpty()) {
            deleteNext(sftpUtil, deleteFileList)
        }
        println("全部删除完成!")
        if (uploadFileList.isNotEmpty()) {
            sftpUtil.upload(uploadFileList, parentPath)
            //upload(SFTPUtil, uploadFileList, parentPath)
        }
        println("全部上传完成!")
        sftpUtil.logout()
    } else println("登录sftp失败!")

}

// 更新上传
private fun upload(sftpUtil: SFTPUtil, uploadFileList: MutableList<String>, parentPath: String) {
    val sftpMap = appConfig.user[YamlUtil.unpackEnvName]!!["sftp"] as Map<String, String>
    val value = uploadFileList.removeAt(0)
    var path = sftpMap["uploadSFTPPath"] + value
    path = path.replace(parentPath, "")
//println(value, path)
    sftpUtil.upload(value, path)
    if (uploadFileList.isNotEmpty())
        upload(sftpUtil, uploadFileList, parentPath)
}

// 删除文件
private fun deleteNext(sftpUtil: SFTPUtil, deleteFileList: MutableList<String>) {
    val sftpMap = appConfig.user[YamlUtil.unpackEnvName]!!["sftp"] as Map<String, String>
    val value = deleteFileList.removeAt(0)
    val path = sftpMap["uploadSFTPPath"] + value
    sftpUtil.delete(path)
    println("删除=$value, 还剩 ${deleteFileList.size}个")
    if (deleteFileList.isNotEmpty())
        deleteNext(sftpUtil, deleteFileList)
}